package com.ysqcould.message.utils.sms;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ysqcould.allocation.domain.WxUserContacts;
import com.ysqcould.allocation.mapper.WxUserContactsMapper;
import com.ysqcould.common.core.domain.AjaxResult;
import com.ysqcould.common.core.domain.entity.JbUser;
import com.ysqcould.common.utils.spring.SpringUtils;
import com.ysqcould.message.domain.Sms;
import com.ysqcould.message.domain.SmsApp;
import com.ysqcould.message.domain.SmsContent;
import com.ysqcould.message.mapper.SmsAppMapper;
import com.ysqcould.message.mapper.SmsContentMapper;
import com.ysqcould.message.mapper.SmsMapper;
import com.ysqcould.system.mapper.SysUserMapper;

import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.ysqcould.message.utils.sms.CreateSign.createSign;
import static java.util.UUID.randomUUID;

/**
 * @author jcd
 * 短信发送工具类
 */
public class SmsUtil {

    /**
     * 短信发送
     * @param asId
     * @param id
     * @return
     */
    public static AjaxResult sendSmsMessage(Long asId, Long id)  {
        SmsContentMapper smsContentMapper = SpringUtils.getBean(SmsContentMapper.class);
        SmsMapper smsMapper = SpringUtils.getBean(SmsMapper.class);
        SysUserMapper sysUserMapper = SpringUtils.getBean(SysUserMapper.class);
        SmsAppMapper smsAppMapper = SpringUtils.getBean(SmsAppMapper.class);
        WxUserContactsMapper wxUserContactsMapper = SpringUtils.getBean(WxUserContactsMapper.class);
        SmsContent content = smsContentMapper.selectSmsContentById(id);
        if (content.getSmsCount()==0){
            return AjaxResult.error(502,"您的短信发送功能次数已用完，请联系管理员恢复额度");
        }
        Sms sms = smsMapper.findFirst(content.getTemplateCode());
        SmsApp smsApp = smsAppMapper.findFirst(content.getAppId());
        JbUser user = sysUserMapper.findFirst(asId);
        if (ObjectUtil.isEmpty(content)&&ObjectUtil.isEmpty(smsApp)){
            return  AjaxResult.error(501,"数据为空");
        }
        String s1 = null;
        try {
            StringBuilder tokenBuf=new StringBuilder("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential");
            tokenBuf.append("&appid=").append(smsApp.getAppId());
            tokenBuf.append("&secret=").append(smsApp.getSercet());
            s1 = HttpRequest.get(tokenBuf.toString()).execute().body();
        } catch (HttpException e) {
            throw new RuntimeException(e);
        }
        Integer count=0;
        JSONObject object = JSONObject.parseObject(s1);
        String token = object.getString("access_token");
        String[] split = content.getConcatId().split(",");
        for (String concatId : split) {
            WxUserContacts contacts = wxUserContactsMapper.findById(concatId);
            String url = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + token ;
            Map<String, Object> map =  new HashMap<String, Object>();
            /*Map<String, Object> cloudBase =  new HashMap<String, Object>();*/
            map.put("path", "/pages/web/index");
            map.put("query","pageType=0&param="+concatId);
            map.put("env_version", "release");
            map.put("expire_type", 1);
            map.put("expire_interval", 30);
            String result = HttpRequest.post(url)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(map))
                    .execute().body();
            System.out.println(result);
            sendSmsConcatId(contacts,content,sms,result,user);
            count++;
        }
        content.setSmsCount(content.getSmsCount()-count);
        return AjaxResult.success(smsContentMapper.updateSmsContent(content));
    }
    /**
     *
     * @param contacts 联系人
     * @param content 内容
     * @param sms     短信模板
     * @param result  生成的微信短链
     */
    private static void sendSmsConcatId(WxUserContacts contacts, SmsContent content, Sms sms, String result,JbUser user)  {
        //String url = "http://8.141.156.164/api/sms/send/text/single";
        Map<String, String> map =  new HashMap<String, String>();
        JSONObject object = JSONObject.parseObject(result);
        Map<String,String>msgMap=new HashMap<>();
        final String s = content.getTemplateParam().replace("${name}", contacts.getName());
        final String link = s.replace("${url}", object.getString("url_link") + "\n");
        final String smsMsg = link.replace("${appName}", user.getName());
        msgMap.put("content",smsMsg);
        String str = JSON.toJSONString(msgMap);
        System.out.println(str);
        map.put("action", sms.getAction());
        map.put("phoneNumbers", contacts.getMobile());
        map.put("signName", sms.getSignName());
        map.put("templateCode", sms.getTemplateCode());
        map.put("templateParam",str);
        System.out.println(map.toString());
        Long currentUtcTime = Date.from(Instant.now()).getTime();
        String timestamp = ""+currentUtcTime;
        String signatureNonce = randomUUID().toString();
        String signature = createSign(sms.getAk(), sms.getSk(), map, timestamp, signatureNonce);
        try {
            String results = HttpRequest.post(sms.getUrl())
                    .header("Content-Type", "application/json")
                    .header("signature",signature)
                    .header("timestamp",timestamp)
                    .header("access-key",sms.getAk())
                    .header("signature-nonce",signatureNonce)
                    .body(JSON.toJSONString(map, SerializerFeature.MapSortField))
                    .execute().body();
            System.out.println(results);
        } catch (HttpException e) {
            e.printStackTrace();
        }
    }
}
